<?php

function revisit_add_page($id) {
    return drupal_get_form('revisit_edit_form',$id);
}

function revisit_edit_page($id) {
    return drupal_get_form('revisit_edit_form', $id);
}

function revisit_edit_form($form, &$form_state) {
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {
        $form['#farmer'] = $form_state['farmer'];
    }
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('revisit', 'revisit_id', $id);
        if (empty($record)) {
            drupal_set_message(t('回访信息不存在！'), 'status', FALSE);
            return $form;
        }
        $form['#revisit_id'] = $id;
    }
    // 判断用户角色
    if(!nonghua_user_access('revisit', 'view', $id, isset($record)&& !empty($record) ? $record->author_uid:0,isset($record)&& !empty($record) ?  $record->farmer_id:'') ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    _insert_farmer_select_info($form,$form_state,isset($record)&&!empty($record) ?$record :'');
    $form['visit_date'] = array(
        '#type' => 'metercomm_date',
        '#title' => 'h=回访日期',
        '#default_value' =>_date_db_2_form(isset($record)&&!empty($record)  ? $record->visit_date : ''),
        '#size' => 32,
    );
    $form['plant'] = _insert_plant_selection_form($form,$form_state,isset($record)&&!empty($record) ? $record->plant_id:'');
    $form['unit_yield'] = array(
        '#type' => 'textfield',
        '#title' => '单量（公斤/亩）',
        '#default_value' => isset($record)&&!empty($record) ? $record->unit_yield : '0',
    );
    $form['net_income'] = array(
        '#type' => 'textfield',
        '#title' => '纯收益（亩）',
        '#default_value' => isset($record)&&!empty($record) ? $record->net_income : '0',
    );
    $form['contrast_yield'] = array(
        '#type' => 'textfield',
        '#title' => '对照产量',
        '#default_value' => isset($record)&&!empty($record) ? $record->contrast_yield : '0',
    );
    $form['contrast_income'] = array(
        '#type' => 'textfield',
        '#title' => '对照收益',
        '#default_value' => isset($record)&&!empty($record) ? $record->contrast_income : '0',
    );
    $form['content'] = array(
        '#type' => 'textarea',
        '#title' => '回访内容',
        '#default_value' => isset($record)&&!empty($record) ? $record->content : '',
        '#maxlength' => 200,
        '#attributes'=>array('placeholder'=>'最多输入200字。')
    );
    insert_special_activities($form,$form_state,isset($record) && !empty($record)?$record:'');
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(1) !='add' ? '修改' : '添加',
        '#access' => nonghua_user_access('revisit', 'edit', $id, isset($record)&&!empty($record) ? $record->author_uid:0,isset($record)&& !empty($record) ? $record->farmer_id:'') ,
    );
    return $form;
}

function revisit_edit_form_validate($form, &$form_state) {

    if(!empty($form_state['values']['unit_yield'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['unit_yield']) || (strlen(explode('.',$form_state['values']['unit_yield'])[0])>8)) {
            form_set_error('unit_yield',  "单量格式错误");
        }
    }
    if(!empty($form_state['values']['net_incom'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['net_incom']) || (strlen(explode('.',$form_state['values']['net_incom'])[0])>8)) {
            form_set_error('unit_yield',  "纯收益格式错误");
        }
    }
    if(!empty($form_state['values']['contrast_yield'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['contrast_yield']) || (strlen(explode('.',$form_state['values']['contrast_yield'])[0])>8)) {
            form_set_error('unit_yield',  "对照产量格式错误");
        }
    }
    if(!empty($form_state['values']['contrast_income'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['contrast_income']) || (strlen(explode('.',$form_state['values']['contrast_income'])[0])>8)) {
            form_set_error('unit_yield',  "对照收益格式错误");
        }
    }
    if(empty($form_state['values']['farmer_id'])){
        form_set_error('farmer_name', '必须选择 农户.');
    }
    if(empty($form_state['values']['plant'])){
        form_set_error('plant', '必须填写 农作物.');
    }
    if(!empty($form_state['values']['plant'])){
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false);
        if(empty($plant_id)){
            form_set_error('plant', "作物信息不存在！");
        }
    }
}

function revisit_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;

    if (arg(1) =='add') { //add new revisit
        $nid = db_insert('revisit') // Table name no longer needs {}
                ->fields(array(
                    'visit_date' => _date_form_2_db($form_state['values']['visit_date']),
                    'farmer_id' => $form_state['values']['farmer_id'],
                    'plant_id' =>get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                    'unit_yield' => $form_state['values']['unit_yield'],
                    'net_income' => $form_state['values']['net_income'],
                    'contrast_yield' => $form_state['values']['contrast_yield'],
                    'contrast_income' => $form_state['values']['contrast_income'],
                    'content' => $form_state['values']['content'],
                    'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                    'author_uid' => $form_state['values']['farmer_id'],
                    'timestamp' => time(),))
                ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            if(!empty($_GET['farmer_id'])){
                drupal_goto('revisit/add/'.$nid,array('query' => array('farmer_id' => $_GET['farmer_id'])));
            }
            if(!empty($_GET['addr_id'])){
                drupal_goto('revisit/list',array('query' => array('addr_id' => $_GET['addr_id'])));
            }
            drupal_goto('revisit/add/'.$nid);
        }

    } else {
        $nid = db_update('revisit')// edit exsting store. todo: update only modified fields
        ->fields(array(
            'visit_date' => _date_form_2_db($form_state['values']['visit_date']),
            'farmer_id' => $form_state['values']['farmer_id'],
            'plant_id' =>get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
            'unit_yield' => $form_state['values']['unit_yield'],
            'net_income' => $form_state['values']['net_income'],
            'contrast_yield' => $form_state['values']['contrast_yield'],
            'contrast_income' => $form_state['values']['contrast_income'],
            'content' => $form_state['values']['content'],
            'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
//            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->condition('revisit_id', $id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
        if(!empty($_GET['farmer_id'])){
            drupal_goto('revisit/list',array('query' => array('farmer_id' => $_GET['farmer_id'])));
        }
        if(!empty($_GET['addr_id'])){
            drupal_goto('revisit/list',array('query' => array('addr_id' => $_GET['addr_id'])));
        }

    }
}
